<?php

namespace App\Models;

use Dcat\Admin\Admin;
use Dcat\Admin\Traits\HasDateTimeFormatter;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class AdminOperationLog extends Model
{
    use HasDateTimeFormatter;
    
    protected $table = 'admin_operation_log';

    protected $fillable = ['user_id', 'user_name', 'gid', 'path', 'method', 'ip', 'input', 'description', 'detail', 'relation_table', 'relation_id', 'type'];
    protected $cats = [
        'description' => 'json',
        'detail' => 'json',
    ];

    const TYPE_LOGIN = 1;
    const TYPE_CREATE = 2;
    const TYPE_EDIT = 3;
    const TYPE_DELETE = 4;
    const TYPE_OTHER = 5;

    public static $methodColors = [
        'GET'    => 'green',
        'POST'   => 'yellow',
        'PUT'    => 'blue',
        'DELETE' => 'red',
    ];

    public static $methods = [
        'GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'PATCH',
        'LINK', 'UNLINK', 'COPY', 'HEAD', 'PURGE',
    ];

    /**
     * Log belongs to users.
     *
     * @return BelongsTo
     */
    public function user() : BelongsTo
    {
        return $this->belongsTo(AdminUser::class, 'user_id', 'id');
    }

    public function setDescriptionAttribute($value)
    {
        $this->attributes['description'] = $value ? json_encode($value) : json_encode([]);
    }

    public function getDescriptionAttribute($value)
    {
        return $value ? json_decode($value, true) : [];
    }
}
